//
// Created by Administrator on 2020/3/3 0003.
//

#include "log.h"
#include "android/bitmap.h"
#include <jni.h>
#include <string>
#include <stdio.h>
#include <queue>


jobject generateBitmap(JNIEnv *pEnv, uint32_t width, uint32_t height);

extern "C"
JNIEXPORT jobject JNICALL
Java_com_hrg_gys_clfr_myapplication_JniData_doBitmap(JNIEnv *env, jclass clazz, jobject bitmap) {

    AndroidBitmapInfo androidBitmapInfo;
    AndroidBitmap_getInfo(env, bitmap, &androidBitmapInfo);  /*获得图片的信息*/
    uint32_t width = androidBitmapInfo.width;
    uint32_t height = androidBitmapInfo.height;
    LOGD("width is %d height is %d", width, height);
    void *bitmapPixels;
    AndroidBitmap_lockPixels(env, bitmap, &bitmapPixels); /*bitmap的像素值 输值给bitmapPixels*/
    uint32_t *newBitmapPixels = new uint32_t[width * height];
    /*左右像素替换*/
    int whereToGet = 0;
    for (int y = 0; y < height; ++y) {
        for (int x = width - 1; x >= 0; x--) {
            uint32_t pixel = ((uint32_t *) bitmapPixels)[whereToGet++];
            newBitmapPixels[width * y + x] = pixel;
        }
    }
    /*newBitmapPixels的值输值给bitmapPixels 直接修改原bitmap，此时只要用到该资源的bitmap即使没重新设值都会改变*/
//    memcpy(((uint32_t *) bitmapPixels), newBitmapPixels, sizeof(uint32_t) * width * height);
//    AndroidBitmap_unlockPixels(env, bitmap);
//    return bitmap;
    /*新生成bitmap输值*/
    jobject newBitmap = generateBitmap(env, width, height);
    void *resultBitmapPixels;
    AndroidBitmap_lockPixels(env, newBitmap, &resultBitmapPixels);
    /*newBitmapPixels的值输值给resultBitmapPixels*/
    memcpy(((uint32_t *) resultBitmapPixels), newBitmapPixels, sizeof(uint32_t) * width * height);
    AndroidBitmap_unlockPixels(env, newBitmap);
    delete[] newBitmapPixels;
    return newBitmap;

}
/**
 * 通过反射生成新的bitmap对象
 * @param env
 * @param width
 * @param height
 * @return
 */
jobject generateBitmap(JNIEnv *env, uint32_t width, uint32_t height) {
    jclass bitmapClass = env->FindClass("android/graphics/Bitmap");
    jmethodID createBitmap = env->GetStaticMethodID(bitmapClass, "createBitmap",
                                                    "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
    jclass config = env->FindClass("android/graphics/Bitmap$Config");
    jmethodID valueOf = env->GetStaticMethodID(config, "valueOf",
                                               "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
    jobject config8 = env->CallStaticObjectMethod(config, valueOf,
                                                  env->NewStringUTF("ARGB_8888"));
    AndroidBitmapFormat format=ANDROID_BITMAP_FORMAT_RGBA_8888;
    jobject jobject1 = env->CallStaticObjectMethod(bitmapClass, createBitmap, width, height,
                                                   config8);

    return jobject1;
}

